// pages/home/index.js
const app = getApp()
import {
  urls
} from '../../api/urls'
import {
  queryNotice,
  get_fun_list,
  img_scrool_list,
  property_search_top,
  share_by_property,
  check_Login,
  getMobile,
  check_mobile,
  get_para,
  user_log_record,
  property_search_top10,
  get_default_property
} from '../../api/request'
Page({
  data: {
    qr_code: '', //小程序码
    qrcode_dis: true, //二维码现实标志
    appid_secret: [],
    share_info: [],
    cur_property_code: '',
    cur_property_name: '',
    cur_property_nums: '0', //小区登录使用次数
    cur_job: '加载中...', //当前待办事项
    cur_street_name: '',
    cur_room_code: '', //当前门牌号
    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 500,
    boardcast_info: [],
    fun_list: [],
    img_scrool_list: [],
    value: "",
    appid: "", //'wx9f66c7f0543a6f00'
    secret: "", //45dc2b456acb40aa2da943dd60b71c11'
    openid: "",
    userInfo: {},
    hasUserInfo: false,
    userStatus: '',

    select: false,
    select_list: [],
    from_openid: '',
    from_name: '',
    from_property_code: '',
    from_property_name: '',
    visitTotal: '--', //昨日用户数
    total_yestoday_users: '--', //昨日新增数
    total_date: '', //统计日期
    property_opened_nums: '0',
    property_opening_nums: '0',
    share_Pv: '--', //转发次数
    share_Uv: '--', //转发人数
  },

  getUserInfo: function (e) {
    var userInfo = e.detail.userInfo
  },

  //二维码是否显示  
  dis_qr_code() {
    var m_qrcode_dis = !this.data.qrcode_dis
    this.setData({
      qrcode_dis: m_qrcode_dis
    })
  },

  get_Date_str: function (today, addDayCount, formatstr) {
    var date;
    if (today) {
      date = new Date(today);
    } else {
      date = new Date();
    }
    date.setDate(date.getDate() + addDayCount); //获取AddDayCount天后的日期 
    var y = date.getFullYear();
    var m = date.getMonth() + 1; //获取当前月份的日期 
    var d = date.getDate();
    if (m < 10) {
      m = '0' + m;
    };
    if (d < 10) {
      d = '0' + d;
    };
    switch (formatstr) {
      case "yyyy-mm-dd":
        return y + "-" + m + "-" + d;
        break;
      case "yyyy年mm月dd":
        return y + "年" + m + "月" + d + "日";
        break;
      case "yyyymmdd":
        return y + m + d;
        break;
    }
  },


  onLoad: function (options) {

    //带参数测试
    //    options.from_property_code = '44'
    //    options.from_openid = 'oJJi55VNIjRJb7uou0OKuZEyxLKc'

    //云调用初始化
    wx.cloud.init({
      env: "yzwdj-yzwdj"
    })

    this.getUserInfo;

    //检查是否通过地图切换小区过来
    var m_property_code = wx.getStorageSync('switch_code')
    if (m_property_code) {
      wx.setStorageSync('switch_code', '') //本次有效
      this.setData({
        cur_property_code: m_property_code,
      })
      console.log('-----------通过地图切换小区------------', m_property_code)
      app.globalData.cur_property_code = m_property_code
      wx.setStorageSync('property_code', m_property_code)
      this.get_appid();
      return;
    }

    //判断通过扫描小区定制物业代码小程序进入
    if (options.scene) {
      this.setData({
        from_property_code: options.scene,
        cur_property_code: options.scene,
      })
      //设置为分享的默认小区    
      app.globalData.cur_property_code = options.scene;
      console.log('----------cur_property_code=' + this.data.cur_property_code)
      wx.setStorageSync('property_code', options.scene)
      //  ---- record....
      this.get_appid()
      return
    }

    //判断是否通过分享来的启动
    if (options.from_property_code) {
      this.setData({
        from_openid: options.from_openid,
        from_name: options.from_name,
        from_property_code: options.from_property_code,
        from_property_name: options.from_property_name,
        cur_property_code: options.from_property_code,
        cur_property_name: options.from_property_name,
        cur_street_name: options.from_street_name,
        cur_job: options.from_cur_job,
      })
      //设置为分享的默认小区    
      app.globalData.cur_property_code = options.from_property_code;
      app.globalData.cur_property_name = options.from_property_name;
      app.globalData.cur_street_name = options.from_street_name;
      app.globalData.cur_job = options.from_cur_job;
      wx.setStorageSync('property_code', options.from_property_code)
      //  ---- record....
      this.get_appid()
      return
    }

    //检查手机本地过去使用过没property_code
    var m_property_code = wx.getStorageSync('property_code')
    if (m_property_code) { //手机保留过去使用的m_property_code
      this.setData({
        cur_property_code: m_property_code,
      })
      console.log('-----------自动定位上次使用的小区------------', m_property_code)
      app.globalData.cur_property_code = m_property_code
      wx.setStorageSync('property_code', m_property_code)
      this.get_appid();
      return;
    }

    //第一次通过搜索小程序进入  获取默认小区编号
    var data = {
      para: ['DEFAULT_PROPERTY']
    }
    get_default_property(data).then(res => {
      this.setData({
        cur_property_code: res.data[0].PROPERTY_CODE,
        cur_property_name: res.data[0].PROPERTY_NAME,
        cur_street_name: res.data[0].STREET_NAME,
        cur_job: res.data[0].CUR_JOB,
      })
      app.globalData.cur_property_code = this.data.cur_property_code;
      app.globalData.cur_property_name = this.data.cur_property_name;
      app.globalData.cur_street_name = this.data.cur_street_name;
      app.globalData.cur_job = this.data.cur_job;
      wx.setStorageSync('property_code', this.data.cur_property_code)
      this.get_appid();
    })
  },

  // getappid    
  get_appid() {
    //获取APPID/SECRET
    var data = {
      para: ['YZWDJ_APPID_SECRET']
    }
    get_para(data).then(res => {
      var para_value = res.data[0].PARA_VALUE
      this.setData({
        appid_secret: para_value.split('/')
      })
      app.globalData.cur_appid = this.data.appid_secret[0]
      app.globalData.cur_secret = this.data.appid_secret[1]
      console.log('---new user appid=' + this.data.appid_secret[0] + '-----secret=' + this.data.appid_secret[1])

      this.getopenid()
    })
  },

  //每次进来都要 获取 openid
  getopenid() {
    const _this = this
    wx.login({
      //获取code 拿openid、sessionKey
      success: (res) => {
        const _this = this
        wx.cloud.callFunction({
          name: "getOpenid", //云函数
          data: {},
          success: res => {
            var openid = res.result.OPENID
            _this.setData({
              openid
            })
            console.log('--------get openid[' + openid + ']------')
            app.globalData.cur_my_openid = openid

            //查询昨天的数据
            var m_begin_date = this.get_Date_str(null, -1, "yyyymmdd")
            var m_end_date = this.get_Date_str(null, -1, "yyyymmdd")
            var m_yestoday = this.get_Date_str(null, -1, "yyyy-mm-dd")

            wx.cloud.callFunction({
              name: "total", //云函数
              data: {
                begin_date: m_begin_date,
                end_date: m_end_date
              },
              success(res) {
                if (res.result.errCode == 0) {
                  _this.setData({
                    visitTotal: res.result.list[0].visitTotal,
                    total_date: m_yestoday,
                    share_Pv: res.result.list[0].sharePv,
                    share_Uv: res.result.list[0].shareUv,
                  })
                } else {
                  _this.setData({
                    total_date: '----年--月--日',
                    visitTotal: "--",
                    share_Pv: '--',
                    share_Uv: '--',
                  })
                }

                _this.home_main() //刷新主页面

              },
              fail(res) {
                _this.setData({
                  total_date: res.result.list[0].refDate,
                  visitTotal: "--",
                  share_Pv: '--',
                  share_Uv: '--',
                })
                _this.home_main() //刷新主页面

              },
            })

          },
          fail(res) {
            console.log("-----get_openid 获取失败-----", res)
          }
        })

      }
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  //获取信息列表
  queryNotice(property_code) {
    var data = {
      para: [property_code, "01", "5"],
    }
    console.log('---------- boardcast=', '["' + property_code + '","01","5"]')
    queryNotice(data).then(res => {
      this.setData({
        boardcast_info: res.data
      })
    })
  },
  //获取菜单
  get_fun_list(data) {
    data = {
      para: [data]
    }
    get_fun_list(data).then(res => {
      this.setData({
        fun_list: res.data
      })
    })

  },
  //轮播
  img_scrool_list(data) {
    data = {
      para: [data, "HOME"]
    }

    img_scrool_list(data).then(res => {
      this.setData({
        img_scrool_list: res.data
      })
    })
  },
  //跳页面
  toPage(e) {
    const certification_statusTrue = () => {
      var url = '/' + e.currentTarget.dataset.fun_goto_url.trim()
      var m_para_pos = e.currentTarget.dataset.fun_goto_url.indexOf('?')
      wx.setStorageSync('type', e.currentTarget.dataset.fun_goto_url.split('?type=')[1])
      if (m_para_pos > 0) { //有参数
        url = '/' + e.currentTarget.dataset.fun_goto_url.substring(0, m_para_pos)
      }
      wx.navigateTo({
        url
      })
    }

    if (e.currentTarget.dataset.auth == '1' && !wx.getStorageSync('certification_status')) { //针对投票要求实名认证
      wx.navigateTo({
        url: '/pages/autWay/autWay'
      })
    } else {
      certification_statusTrue()
    }
  },

  halSearch(e) {},

  //小程序分享信息查询
  share_by_property(property_code) {
    var data = {
      para: [property_code]
    }
    share_by_property(data).then(res => {
      this.setData({
        share_info: res.data
      })
      app.globalData.share_title = res.data[0].SHARE_TITLE
      app.globalData.share_img_url = res.data[0].SHARE_IMG_URL

      this.user_log_record(app.globalData.cur_my_openid, app.globalData.cur_my_name, '', '', app.globalData.cur_property_code,
        app.globalData.cur_property_name, '1', '1', '1')
    })
  },

  //主页面-验证
  home_main() {
    const _this = this
    this.check_Login(_this.data.openid, _this.data.cur_property_code);
    this.qr_code_flush()
  },

  qr_code_flush() {
    let that = this
    var m_path = 'pages/home/index?from_property_code=' + app.globalData.cur_property_code + '&from_openid=' + app.globalData.cur_my_openid
    wx.cloud.callFunction({
      name: "get_qrcode", //128字节带参数调用
      data: {
        path: m_path,
        width: 100
      },

      success(res) {
        that.setData({
          qr_code: res.result.buffer.fileID
        })
      },
    })
  },


  //主页面-信息刷新
  home_flush() {
    const _this = this;
    console.log('---- home page flush openid[' + _this.data.openid + '],property_code[' + app.globalData.cur_property_code +
      ']-----');
    _this.setData({
      cur_my_openid: app.globalData.cur_my_openid,
      cur_my_name: app.globalData.cur_my_name,
      cur_property_code: app.globalData.cur_property_code,
      cur_property_name: app.globalData.cur_property_name,
      cur_street_name: app.globalData.cur_street_name,
      cur_job: app.globalData.cur_job,
      cur_room_code: app.globalData.cur_room_code,
      cur_property_nums: app.globalData.cur_perperty_nums,
    })


    _this.get_fun_list(app.globalData.cur_property_code); //刷新功能菜单页面
    _this.img_scrool_list(app.globalData.cur_property_code); //刷新图片滚动
    _this.queryNotice(app.globalData.cur_property_code) //刷新公告栏
    _this.share_by_property(app.globalData.cur_property_code); //刷新分享链接信息

    _this.qr_code_flush()
  },


  //检测登录状态
  check_Login(openid, property_code) {
    const _this = this;
    var m_certification_ret = ""; //实名认证状态
    var data = {
      para: [openid,
        property_code
      ],
    }
    check_Login(data).then(res => {
      //保存全局变量
      m_certification_ret = res.data[0].ERRORCODE

      function setGlobalData() {
        app.globalData.cur_my_name = res.data[0].ROOM_NAME
        app.globalData.cur_property_code = res.data[0].PROPERTY_ID
        app.globalData.cur_property_name = res.data[0].PROPERTY_NAME
        app.globalData.cur_job = res.data[0].CUR_JOB
        app.globalData.cur_street_name = res.data[0].STREET_NAME
        app.globalData.cur_room_code = res.data[0].ROOM_CODE
        app.globalData.cur_city = res.data[0].CITY
        app.globalData.cur_district = res.data[0].DISTRICT
        app.globalData.cur_property_nums = res.data[0].PROPRTTY_NUMS
        app.globalData.property_list = res.data[0].PROPERTY_LIST
        if (res.data[0].SIGNATURE_NAME != '') {
          app.globalData.signature_name = '【' + res.data[0].SIGNATURE_NAME + '】' //个人签名
        } else {
          if (app.globalData.cur_my_name) {
            app.globalData.signature_name = '【' + app.globalData.cur_my_name + '】' //默认为微信昵称
          } else {
            app.globalData.signature_name = '' //暂时没有签名
          }
        }
        app.globalData.phoneNumber = res.data[0].MOBILE

        _this.setData({
          cur_my_name: res.data[0].ROOM_NAME,
          cur_job: res.data[0].CUR_JOB,
          cur_street_name: res.data[0].STREET_NAME,
          cur_property_name: res.data[0].PROPERTY_NAME,
          cur_room_code: res.data[0].ROOM_CODE,
          cur_property_nums: res.data[0].PROPERTY_NUMS,
          property_opened_nums: res.data[0].PROPERTY_OPENED_NUMS,
          property_opening_nums: res.data[0].PROPERTY_OPENING_NUMS,
        })
      }

      if (m_certification_ret == '-100') {
        this.setData({
          userStatus: '手机号授权'
        })
        wx.setStorageSync('certification_status', false)
        app.globalData.cur_certification = '0'
        this.user_log_record(app.globalData.cur_my_openid, app.globalData.cur_my_name, '', '', app.globalData.cur_property_code,
          app.globalData.cur_property_name, '1', '11', '1')
        console.log('------new user,goto login get mobile ------')
        wx.navigateTo({
          url: '/pages/login/index'
        })
      }

      if (m_certification_ret == '0') { //已授权过手机号，但没实名认证
        this.setData({
          userStatus: '未通过实名认证',
          cur_property_name: res.data[0].PROPERTY_NAME,
          cur_job: res.data[0].CUR_JOB,
          cur_street_name: res.data[0].STREET_NAME,
          cur_my_name: res.data[0].ROOM_NAME,
          cur_property_nums: res.data[0].PROPERTY_NUMS,
          cur_room_code: '请实名认证',
          property_opened_nums: res.data[0].PROPERTY_OPENED_NUMS,
          property_opening_nums: res.data[0].PROPERTY_OPENING_NUMS,
        })
        wx.setStorageSync('certification_status', false)
        app.globalData.cur_certification = m_certification_ret
        app.globalData.cur_property_name = res.data[0].PROPERTY_NAME
        app.globalData.phoneNumber = res.data[0].MOBILE
        app.globalData.cur_job = res.data[0].CUR_JOB
        app.globalData.cur_street_name = res.data[0].STREET_NAME
        app.globalData.cur_property_name = res.data[0].PROPERTY_NAME
        app.globalData.cur_my_name = res.data[0].ROOM_NAME
        if (app.globalData.cur_my_name) {
          app.globalData.signature_name = '【' + app.globalData.cur_my_name + '】'
        }
        app.globalData.cur_city = res.data[0].CITY
        app.globalData.cur_district = res.data[0].DISTRICT
        app.globalData.cur_property_nums = res.data[0].PROPRTTY_NUMS
        app.globalData.property_list = res.data[0].PROPERTY_LIST

        console.log('----- openid[' + app.globalData.cur_my_openid + '] 未通过实名认证---property_code=' + app.globalData.cur_property_name +
          '----')

        this.user_log_record(app.globalData.cur_my_openid, app.globalData.cur_my_name, '', '', app.globalData.cur_property_code,
          app.globalData.cur_property_name, '1', '1', '1')

        this.img_scrool_list(app.globalData.cur_property_code)
        this.queryNotice(app.globalData.cur_property_code)
        this.get_fun_list(this.data.cur_property_code);
        this.share_by_property(this.data.cur_property_code); //刷新分享链接  
      }


      if (m_certification_ret == '1') {
        this.setData({
          userStatus: '已通过实名认证',
        })
        wx.setStorageSync('certification_status', true)
        app.globalData.cur_my_name = '1'
        app.globalData.cur_certification = m_certification_ret
        setGlobalData()

        console.log('----- main openid[' + app.globalData.cur_my_openid + '] 已通过实名认证-------')
        this.img_scrool_list(app.globalData.cur_property_code)
        this.queryNotice(app.globalData.cur_property_code)

        this.user_log_record(app.globalData.cur_my_openid, app.globalData.cur_my_name, '', '', app.globalData.cur_property_code,
          app.globalData.cur_property_name, '1', '1', '1')
        this.get_fun_list(this.data.cur_property_code);
        this.share_by_property(this.data.cur_property_code); //刷新分享链接  
      }
    })
  },

  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    wx.setStorageSync('userInfo', e.detail.userInfo)
  },

  //手机号实名认证
  check_mobile(openid, mobile) {
    var data = {
      para: [openid, mobile]
    }
    check_mobile(data).then(res => {
      wx.switchTab({
        url: '/pages/home/index'
      })
      if (res.data[0].ERRORCODE == '0') wx.setStorageSync('certification_status', false)
    })
  },
  //小程序关键使用行为记录保存
  user_log_record(cur_openid, cur_username, from_openid, from_username, from_property_code, from_property_name,
    share_channel, log_type, log_msg) {
    var data = {
      para: [cur_openid,
        cur_username,
        from_openid,
        from_username,
        from_property_code,
        from_property_name,
        share_channel,
        log_type,
        log_msg,
      ],
    }
    user_log_record(data).then(res => {
      console.log('---user_log_record=', log_msg, res.data[0].ERRORMSG)
    })
  },

  //查看全部
  boardcast_all() {
    wx.setStorageSync('type', '01')
    wx.navigateTo({
      url: '/pages/cast/index'
    })
  },

  //查看公告详情
  to_read_content(e) {
    wx.navigateTo({
      url: '/pages/xq/index?broadcast_id=' + e.currentTarget.dataset.broadcast_id + '&property_code=' + this.data.cur_property_code
    })
  },

  property() {
    wx.navigateTo({
      url: '/pages/property/index',
    })
  },

  blurInput() {
    this.setData({
      select: false
    })
  },

  bindShowMsg() {
    this.setData({
      select: true
    })
  },
  property_search_top10(property_name_key) {
    var data = {
      para: '["' + property_name_key + '"]',
    }
    property_search_top10(data).then(res => {
      var select_list = res.data
      this.setData({
        select_list
      })
    })
  },
  halchangeSearch(e) {
    this.setData({
      property_name: e.detail.value
    })
    this.property_search_top10(e.detail.value)
  },
  tosarch() {
    wx.navigateTo({
      url: '/pages/xzMap/xzMap'
    })
  },

  contact_click() {
    wx.navigateTo({
      url: '/pages/contact/index',
    })
  },

  goto_url(e) {
    var m_url = e.currentTarget.dataset.url
    if (m_url != null) {
      wx.navigateTo({
        url: m_url
      })
    }
  },

  onLaunch() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '业主我当家更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            wx.showModal({
              title: '业主我当家已有新版本',
              content: '新版本已经上线，请您删除当前小程序，重新搜索打开'
            })
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前你的微信版本过低，无法使用该功能，请升级到最新微信版本后重试！'
      })
    }
  },

  contact_us() {
    wx.navigateTo({
      url: '/pages/home/qrcode',
    })
  },

  // 用户点击右上sha角分享
  onShareAppMessage: function () {
    const _this = this;

    var m_share_path = '/pages/home/index?from_openid=' + app.globalData.cur_my_openid + '&from_name=' + app.globalData.cur_my_name +
      '&from_property_code=' + app.globalData.cur_property_code + '&from_property_name=' + app.globalData.cur_property_name + '&from_street_name=' + app.globalData.cur_street_name +
      '&from_cur_job=' + app.globalData.cur_job + '&share=1'

    return {
      title: app.globalData.share_title,
      path: m_share_path,
      imageUrl: _this.data.share_info[0].SHARE_IMG_URL
    }
  },



})